//==============================================
// Đập trúng bong bóng, tất cả các lổ điều có rat popup
// Đập trúng chồn hoi, trừ điểm
// Đập trúng chuột thỏ, điểm gấp đôi
// Đập chết boss cáo, điểm cực nhiều, đập nhiều lần
// => phát triển thành đi màn, có đấu boss
//==============================================

package Features.RatFeild
{
	import com.greensock.TimelineLite;
	import com.greensock.TweenLite;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextFieldAutoSize;
	
	import org.SFramework.Architechture.SViewNode;
	import org.SFramework.Core.SFramework;
	import org.SUtility.SRandom;
	import org.SUtility.SSequenceScheduler;
	import org.SUtility.SStringFormatter;
	import org.SuiComponents.SuiLabel;
	import org.SuiComponents.SuiProgressBar;
	
	public class RatField extends SViewNode
	{
		private static const MinumunNextRatTime:Number	=	0.4;
		private static const MinumunRatPopup:Number		=	0.6;
		private static const NumberHog:int				=	12;
		private static const RoundTime:int				=	60 * 2;	// 2 minutes
		
		private var mcHand:MovieClip;
		private var readytext:MovieClip;
		private var hogListFree:Vector.<RatHog>	=	new Vector.<RatHog>();
		private var hogListBusy:Vector.<RatHog>	=	new Vector.<RatHog>();
		private var lblScore:SuiLabel;
		private var lblTimer:SuiLabel;
		private var pgbTimer:SuiProgressBar;
		private var subUIContainer:Sprite;
		
		private var lblInfo:SuiLabel;
		
		//================================================
		
		private var timeElapse:Number		=	0.0;
		private var nextRatTime:Number		=	0.0;
		private var scheduler:Scheduler		=	new Scheduler();
		private var isAction:Boolean		=	false;
		private var roundTimeElapse:Number	=	0.0;
		
		//================================================
		
		private var scored:int				=	0;
		
		//================================================
		
		public function RatField()
		{
		}
		
		override public function onInit(initData:Object):Boolean
		{			
			var bg:Sprite	=	SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "background" );
			addChild( bg );
			
			for( var i:int=0; i<NumberHog; i++ )
			{
				var hog:DisplayObject	=	bg.getChildByName( "Hog" + i );
				var index:int			=	bg.getChildIndex( hog );
				bg.removeChildAt( index );
				
				var ratH:RatHog			=	new RatHog();
				ratH.x					=	hog.x;
				ratH.y					=	hog.y;
				ratH.scaleX				=	hog.scaleX;
				ratH.scaleY				=	hog.scaleY;
				ratH.visible			=	false;
				bg.addChildAt( ratH, index );
				
				ratH.addEventListener( MouseEvent.CLICK, handleWhackRat );
				
				hogListFree.push( ratH );
			}
			
			mcHand	=	SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "hand" ) as MovieClip;
			mcHand.startDrag();
			mcHand.mouseEnabled		=	false;
			mcHand.mouseChildren	=	false;
			mcHand.x	=	SFramework.singleton.getStage().mouseX;
			mcHand.y	=	SFramework.singleton.getStage().mouseY;
			addChild( mcHand );
			
			//============
			
			subUIContainer			=	new Sprite();
			subUIContainer.visible	=	false;
			addChild( subUIContainer );			
			
			var scoreBoard:Sprite	=	SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "scoreBoard" );
			scoreBoard.x			=	3;
			scoreBoard.y			=	3;
			subUIContainer.addChild( scoreBoard );		
			
			lblScore			=	new SuiLabel();
			lblScore.fontName	=	"WoodLook";
			lblScore.text		=	"Score";
			lblScore.embedFont	=	true;
			lblScore.autoSize	=	TextFieldAutoSize.LEFT;
			lblScore.textSize	=	20;
			lblScore.textColor	=	0xffeeaa;
			lblScore.enabled	=	true;
			lblScore.x			=	12;
			lblScore.y			=	7;
			subUIContainer.addChild( lblScore );
			
			pgbTimer			=	new SuiProgressBar();
			pgbTimer.setSize( 365.4, 23.05 );
			pgbTimer.x			=	182.05;
			pgbTimer.y			=	7;
			pgbTimer.labelType	=	"none";
			pgbTimer.direction	=	"right";
			pgbTimer.setDisplayObject( SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "pgbTime" ) );
			subUIContainer.addChild( pgbTimer );
			
			lblTimer			=	new SuiLabel();
			lblTimer.fontName	=	"WoodLook";
			lblTimer.text		=	"02:00";
			lblTimer.embedFont	=	true;
			lblTimer.autoSize	=	TextFieldAutoSize.LEFT;
			lblTimer.textSize	=	15;
			lblTimer.textColor	=	0xffeeaa;
			lblTimer.enabled	=	true;
			lblTimer.x			=	337;
			lblTimer.y			=	7;
			subUIContainer.addChild( lblTimer );
			
			readytext				=	SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "readytext" );
			readytext.visible		=	false;
			addChild( readytext );
			
			
			lblInfo				=	new SuiLabel();
			lblInfo.autoSize	=	TextFieldAutoSize.CENTER;
			lblInfo.textSize	=	15;
			lblInfo.y			=	100;
			lblInfo.x			=	100;
			lblInfo.enabled		=	true;
			lblInfo.textColor	=	0xffffff;
			addChild( lblInfo );
			
			SFramework.singleton.runtimeUpdater.addFunction( onFrameUpdate );
			SFramework.singleton.runtimeUpdater.addFunction( onFrameUpdateSecond, null, 1.0 );
			
			return true;
		}
		
		override public function onShow(initData:Object):void
		{
			var schl:SSequenceScheduler	=	new SSequenceScheduler();
			schl.append( null, 1.3 );
			
			for( var i:int=0; i<hogListFree.length; i++ )
				schl.append( applyAnim, 0.15, hogListFree[i] );
			
			schl.append( showTextReady, 0.5 );
			schl.play();
			
			function applyAnim( hog:RatHog ):Boolean
			{
				hog.applySmoke();
				hog.visible	=	true;
				
				return true;
			}
			
			function showTextReady():void
			{
				var tl:TimelineLite	=	new TimelineLite( {onComplete:startPlayGame} );
				readytext.visible	=	true;
				readytext.x			=	200;
				readytext.y			=	-100;			
				tl.append( TweenLite.to( readytext, 0.5, { y: (SFramework.singleton.getHeight() - readytext.height)/2} ) );
				tl.append( TweenLite.to( readytext, 0.5, { delay:1.6, y: SFramework.singleton.getHeight() +100} ) );
				tl.play();			
			}
		}
		
		override public function onHide(onHideComplete:Function):void
		{
			onHideComplete.call();
		}
		
		override public function onResize():void
		{
			
		}
				
		private function stopPlayGame():void
		{
			isAction	=	false;
			for( var i:String in hogListFree )
				TweenLite.delayedCall( Math.random(), hogListFree[i].doPopup, [1, false] );
			
			for( i in hogListBusy )
				hogListBusy[i].enabled	=	false;
			
			mcHand.stopDrag();
			mcHand.x	=	-100;
			mcHand.y	=	-100;
			
			TweenLite.delayedCall( 2.0, Global.viewsCabinet.showLayer, [ShareMacros.MV_DlgSummary] );
		}
		
		private function startPlayGame():void
		{
			readytext.visible	=	false;
			isAction			=	true;
			
			nextRatTime			=	scheduler.getScheduleTime();
			
			pgbTimer.minimum	=	0;
			pgbTimer.maximum	=	RoundTime;
			pgbTimer.value		=	40;
			
			subUIContainer.visible	=	true;
			subUIContainer.y		=	-100;
			TweenLite.to( subUIContainer, 0.5, {y:0} );			
		}
		
		private function onFrameUpdate( deltaTime:Number, totalTime:Number ):void
		{
			if( ! isAction )
				return;
			
			timeElapse	+=	deltaTime;
			if( timeElapse > nextRatTime )
			{
				showRandomRat( nextRatTime );
				timeElapse		=	0;	
				nextRatTime		=	scheduler.getScheduleTime();
				
				// Delay between to rat popup
				nextRatTime		+=	SRandom.randomLeftGaussian( 0.0, 1.5 ) * nextRatTime;
				
				if( nextRatTime < MinumunRatPopup )
					nextRatTime	=	MinumunRatPopup;
				
				lblInfo.text	=	String(nextRatTime);
			}
			
			//=====
			scheduler.updateTime( deltaTime );
			
			for( var i:int=0; i<hogListBusy.length; i++ )
			{
				hogListBusy[i].showTime	-=	deltaTime;
				if( hogListBusy[i].showTime < 0 )
				{
					hogListBusy[i].doHide();
					hogListFree.push( hogListBusy.splice( i, 1 )[0] );
				}				
			}
			
			//=====
			roundTimeElapse	+=	deltaTime;
			if( roundTimeElapse >= RoundTime )
				stopPlayGame();
		}
		
		private function onFrameUpdateSecond( deltaTime:Number, totalTime:Number ):void
		{
			lblScore.text	=	"Score: " + scored;
			lblTimer.text	=	SStringFormatter.formatTime( RoundTime - uint(roundTimeElapse), true );
			
			pgbTimer.value	=	(roundTimeElapse / Number(RoundTime)) * Number(RoundTime);
		}
		
		//==========================================
		
		private function showRandomRat( showTime:Number ):void
		{
			if( hogListFree.length == 0 )
				return;
			
			var seek:int	=	int(Math.floor( Math.random() * hogListFree.length ) );
			if( showTime < MinumunRatPopup )
				showTime	=	MinumunRatPopup;
			hogListFree[seek].doPopup( showTime );
			
			hogListBusy.push( hogListFree.splice( seek, 1 )[0] );
		}
		
		private function handleWhackRat( e:Event ):void
		{
			if( ! isAction )
				return;
			
			mcHand.gotoAndPlay( 2 );
			
			var ratH:RatHog	=	e.currentTarget as RatHog;
			scored			+=	ratH.doWhack();			
			
			var index:int	=	hogListBusy.indexOf( ratH );
			if( index >= 0 )
				hogListFree.push( hogListBusy.splice( index, 1 )[0] );
		}
	}
}